package org.jash.shop;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class HttpUtils {
    private static final Gson gson = new Gson();
    private static final Handler handler = new Handler(Looper.getMainLooper());
    public enum Method {
        GET, POST
    }

    private static InputStream getInputStream(String url, Map<String, ?> params, Method method) throws Exception {
        if (method == Method.GET) {
            url += "?" + params.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining("&"));
        }
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        if (method == Method.GET) {
            connection.setRequestMethod("GET");
        } else if (method == Method.POST) {
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            try(OutputStream os = connection.getOutputStream();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os))) {
                bw.write(gson.toJson(params));
                bw.flush();
            }
        }
        int code = connection.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Http错误: " + code);
        }
        return connection.getInputStream();
    }

    /**
     * 执行GET请求
     * @param url 请求地址
     * @param params 请求参数
     * @param clazz 请求结果的类型
     * @param success 成功处理的回调
     * @param fail 失败处理的回调
     * @param <T> 请求结果的类型
     */
    public static <T> void doGet(String url, Map<String, ?> params, Class<T> clazz, Consumer<T> success, Consumer<Throwable> fail) {
        new Thread(() -> {
            try(InputStream is = getInputStream(url, params, Method.GET);
                JsonReader reader = new JsonReader(new InputStreamReader(is))) {
                T t = gson.fromJson(reader, clazz);
                handler.post(() -> success.accept(t));
            } catch (Exception e) {
                handler.post(() -> fail.accept(e));
            }
        }).start();
    }
    /**
     * 执行POST请求
     * @param url 请求地址
     * @param params 请求参数
     * @param clazz 请求结果的类型
     * @param success 成功处理的回调
     * @param fail 失败处理的回调
     * @param <T> 请求结果的类型
     */
    public static <T> void doPost(String url, Map<String, ?> params, Class<T> clazz, Consumer<T> success, Consumer<Throwable> fail) {
        new Thread(() -> {
            try(InputStream is = getInputStream(url, params, Method.POST);
                JsonReader reader = new JsonReader(new InputStreamReader(is))) {
                T t = gson.fromJson(reader, clazz);
                handler.post(() -> success.accept(t));
            } catch (Exception e) {
                handler.post(() -> fail.accept(e));
            }
        }).start();
    }

;}
